<script setup>
import {onMounted, ref} from 'vue';
import luckysheet from "luckysheet";
import dayjs from "dayjs";
import AnalyesAPI from "@/api/system/analyes.ts";
import {useAnalysetStore} from "@/store/index.ts";
import {transformData} from "@/utils/method";
import Device from "@/components/analysisSheetComponents/component/Device.vue";
import Index from '@/components/analysisSheetComponents/component/index.vue'

const sheetData = ref('')
const checkDialogVisible = ref(false)
const checkTime = ref('')
const processedData = ref([])
const cdatas = ref([])
const analyseStatusPage = useAnalysetStore()
const record_sn = analyseStatusPage.waterForm.record_sn
const switchAdd = ref(true)
const waterForm = ref({
  bzqxhz: {},
   // 复制粘贴
    device: {
    device_name: [],
    device_model: [],
    device_number: [],
  }
})
// 初始化表格
let options = {
  container: "luckysheet", //luckysheet为容器id
  lang: 'zh',
  autoCalculate: true,
  data: [
    {
      "name": "", // 工作表名称
      "color": "", // 工作表颜色
      "index": 0, // 工作表索引
      "status": 1, // 激活状态
      "order": 0, // 工作表的下标
      "column": 6, // 列数
      "defaultRowHeight": 30, // 自定义行高
      "defaultColWidth": 100, // 自定义列宽
      "celldata": [
        // 初始化表格数据，第一行包含表头
        {"r": 0, "c": 0, "v": "样品编号",}, // A1
        {"r": 0, "c": 1, "v": "类型",}, // B1
        {"r": 0, "c": 2, "v": "取样体积",}, // C1
        {"r": 0, "c": 3, "v": "稀释倍数f",}, // D1
        {"r": 0, "c": 4, "v": "吸光度",}, // E1
        {"r": 1, "c": 4, "v": "A",}, // E1
        {"r": 1, "c": 5, "v": "A - Ā₀",}, // E1
        // {"r": 2, "c": 5, "v": "Ā₀=",}, // E1
        {"r": 2, "c": 5, "v": "",}, // E1
        {"r": 0, "c": 6, "v": "浊度稀释ρ1(度)",}, // E1
        {"r": 0, "c": 7, "v": "浊度样品ρ(度)",}, // E1
        {"r": 0, "c": 8, "v": "测定结果",}, // E1
        {"r": 0, "c": 9, "v": "备注",}, // E1
      ], // 初始化数据
      "config": {
        "merge": {
          "0_0": {
            "r": 0, // 起始行
            "c": 0, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_1": {
            "r": 0, // 起始行
            "c": 0, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_2": {
            "r": 0, // 起始行
            "c": 0, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_3": {
            "r": 0, // 起始行
            "c": 0, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_4": {
            "r": 0,  // 起始行
            "c": 4,  // 起始列
            "rs": 1, // 跨越的行数
            "cs": 2  // 横向跨越两列
          },
          "2_5": {
            "r": 0, // 起始行
            "c": 0, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_6": {
            "r": 0, // 起始行
            "c": 0, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_7": {
            "r": 0, // 起始行
            "c": 0, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_8": {
            "r": 0, // 起始行
            "c": 0, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
          "0_9": {
            "r": 0, // 起始行
            "c": 0, // 起始列
            "rs": 2, // 跨越的行数
            "cs": 1  // 跨越的列数
          },
        }, // 合并单元格
        "rowlen": {}, // 表格行高
        "columnlen": { // 设置列宽
          "0": 200, // 第一列宽度 150px
          "1": 150, // 第二列宽度 120px
          "2": 200, // 第三列宽度 180px
          "3": 200, // 第四列宽度 100px
          "4": 200, // 第五列宽度 200px
          "5": 180  // 第六列宽度 150px
        }, // 表格列宽
        "rowhidden": {}, // 隐藏行
        "colhidden": {}, // 隐藏列
        "borderInfo": {}, // 边框
        "authority": {}, // 工作表保护
      },
    }
  ],
  showinfobar: false, // 隐藏信息栏
  showtoolbar: false, // 隐藏工具栏
};
// 在组件挂载后初始化 Luckysheet
onMounted(() => {
  luckysheet.create(options);
  // 获取初始数据并保存在响应式变量中
  sheetData.value = options.data
//   获取工作表信息
  getWaterCapacity()
  // 复制粘贴
  getMethod()
});

// 获取信息( 复制粘贴)
const getMethod = () => {
  waterForm.value.task_name = analyseStatusPage.waterForm.task_number //任务名称
  waterForm.value.method = analyseStatusPage.waterForm.tableItem.test_method
      ? analyseStatusPage.waterForm.tableItem.test_method
      : analyseStatusPage.waterForm.tableItem.test_method_number;//分析方法
  waterForm.value.category_id = analyseStatusPage.waterForm.tableItem.sample_category // 样品类别
  checkTime.value = analyseStatusPage.waterForm.tableItemList.submit_dates
}
// 获取工作表信息
const getWaterCapacity = () => {
  let josn = {
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    task_id: analyseStatusPage.waterForm.taskId,
    // id: 25,
    record_sn: record_sn,
    // record_sn: 40,
  }
  AnalyesAPI.getAnalyseACapacity(josn).then(data => {
    console.log('获取水质容量 A单', data)
     // 复制粘贴
     if (!Array.isArray(data) || data.length !== 0) {
      waterForm.value = data
      sheetData.value = data.configs
      options.data = sheetData.value
      luckysheet.create(options);
      processedData.value = data.adatas
    } else {
      waterForm.value.device = {
        device_name: [],
        device_model: [],
        device_number: [],
      }
    }
  })
}

// 保存新增
const handleAddWaterPh = () => {
  console.log(luckysheet.getLuckysheetfile())
  sheetData.value = luckysheet.getLuckysheetfile();
  options.data = sheetData.value; // 将字符串解析为 JSON
  console.log(options.data)
  const data = options.data[0].data.map(row => {
    return row
        .map(cell => {
          return cell ? {
            field: cell.m || "默认字段",
            value: cell.v || null
          } : null;
        })
        .filter(cell => cell !== null); // 删除 null 值
  });
  console.log(data);
  // 调用函数
  processedData.value = processData(data);
  cdatas.value = transformData(processedData.value)
  if (waterForm.value.check_status !== undefined) {
    delete waterForm.value.check_status
    delete waterForm.value.reviewer_id
  }
  // //   调保存新增接口
  AnalyesAPI.addWaterCapacity({
    ...waterForm.value,
    // record_sn: record_sn,
    record_sn: 44,
    // id: analyseStatusPage.waterForm.id,
    task_id: analyseStatusPage.waterForm.taskId,
    configs: sheetData.value,
    add_form_id: analyseStatusPage.waterForm.add_form_id,
    adatas: processedData.value,
    cdatas: cdatas.value,
  }).then(data => {
    console.log('调接口拿数据', data)
    ElMessage.success('保存成功！')
    switchAdd.value = false
  })
}

const processData = (data) => {
  if (!data || data.length < 2) {
    return [];
  }

  // 提取表头字段
  const headers = [];
  const maxHeaderRows = 2; // 表头行数可扩展

  for (let i = 0; i < data[0].length; i++) {
    let header = "";

    for (let rowIndex = 0; rowIndex < maxHeaderRows; rowIndex++) {
      const field = data[rowIndex]?.[i]?.field || "";

      // 跳过默认字段，选择有效字段
      if (field && field !== "默认字段") {
        header = field;
        break;
      }
    }

    // 跳过空或默认的字段
    if (header && header.trim() !== "") {
      headers.push(header);
    }
  }

  console.log("提取的表头:", headers);

  // 处理数据部分，从表头行之后开始解析
  const result = data.slice(maxHeaderRows).map(row => {
    const rowObject = {};
    headers.forEach((header, index) => {
      const cell = row[index];
      rowObject[header] = cell?.value ?? null; // 如果没有值，则默认 null
    });
    return rowObject;
  });

  // 过滤掉空行（所有字段均为 null 的行）
  return result.filter(row => Object.values(row).some(value => value !== null));
};

 
</script>

<template>
  <div class="card">
    <el-card class="box-card">
      <h1 style="text-align: center">水质 浊度分光光度法分析原始记录</h1>
      <div>SXLPHJ/JL/CX-22-44</div>
      <table class="table">
        <tr style="background-color: #f2f2f2">
          <td>任务编号</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.task_name"/>
          </td>
          <td>采样日期</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.sampling_time"/>
          </td>
          <td>分析日期</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.anal_time"/>
          </td>
        </tr>
        <tr>
          <td>分析方法</td>
          <td colspan="3">
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.method"/>
          </td>
          <td>检出限</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.limit_val"/>
          </td>
        </tr>
        <Device :water-form="waterForm"></Device>
        <tr>
          <td>计算公式</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.js_formula"/>
          </td>
          <td>环境条件</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.temperature"/>
          </td>
          <td>样品类别</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.category_id"/>
          </td>
        </tr>
        <tr>
          <td colspan="6">
            <div class="table-td">
              标准曲线绘制
            </div>
          </td>
        </tr>
        <tr>
          <td>标准贮备液批号</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.zbyph"/>
          </td>
          <td>贮备液浓度(度)</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.zbynd"/>
          </td>
          <td>贮备液有效日期</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.zbyDte"/>
          </td>
        </tr>
        <tr>
          <td colspan="3">测定值</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.cdzOne"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.cdzTow"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.cdzTree"/>
          </td>
        </tr>
      </table>
      <table class="table">
        <tr>
          <td>编号</td>
          <td>01</td>
          <td>02</td>
          <td>1</td>
          <td>2</td>
          <td>3</td>
          <td>4</td>
          <td>5</td>
          <td>6</td>
        </tr>
        <tr>
          <td>标准储备液体积(mL)</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.bzzbytjOne"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.bzzbytjTow"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.bzzbytjTree"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.bzzbytjFour"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.bzzbytjFive"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.bzzbytjSix"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.bzzbytjSeven"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.bzzbytjEight"/>
          </td>
        </tr>
        <tr>
          <td>定容体积(ml)</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.drtjOne"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.drtjTow"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.drtjThree"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.drtjFour"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.drtjFive"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.drtjSix"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.drtjSeven"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.drtjEight"/>
          </td>
        </tr>
        <tr>
          <td>浊度(度)</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.zdOne"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.zdTow"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.zdThree"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.zdFour"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.zdFive"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.zdjSix"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.zdSeven"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.zdEight"/>
          </td>
        </tr>
        <tr>
          <td>吸光度A</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.xgdOne"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.xgdTow"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.xgdThree"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.xgdFour"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.xgdFive"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.xgdjSix"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.xgdSeven"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.xgdEight"/>
          </td>
        </tr>
        <tr>
          <td>A - Ā₀</td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.gsOne"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.gsTow"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.gsThree"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.gsFour"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.gsFive"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.gsSix"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.gsSeven"/>
          </td>
          <td>
            <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                      v-model="waterForm.bzqxhz.gsEight"/>
          </td>
        </tr>
        <tr>
          <td>标准曲线</td>
          <td colspan="8">
            <div style="display: flex;align-items: center;">
              y=
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.bzqxhz.y"/>
            </div>
            <div style="display: flex;align-items: center;">
              x=
              <el-input style="width: 100%;border: 1px solid transparent" placeholder="请输入"
                        v-model="waterForm.bzqxhz.x"/>
            </div>
          </td>
        </tr>
      </table>
      <div id="luckysheet" style="width:100%;height:500px;"></div>
    </el-card>
     <!--    底部公共按钮 (复制粘贴)-->
     <div>
      <Index :water-form="waterForm" :handle-add-water-ph="handleAddWaterPh" :check-time="checkTime"
             :get-water-capacity="getWaterCapacity" :switch-add="switchAdd"></Index>
    </div>
  </div>
</template>

<style scoped>
.card {
  padding: 20px 25px;
}

.table {
  width: 100%;
  border-collapse: collapse; /* 表格边框合并 */
  text-align: left; /* 默认左对齐 */
  font-size: 14px; /* 字体大小 */
  color: #606266; /* 默认字体颜色 */
}

.table th,
.table td {
  border: 1px solid #c2bfbf; /* 表格单元格边框颜色 */
  padding: 12px; /* 单元格内边距 */
}

.table th {
  background: #f5f7fa; /* 表头背景色 */
  font-weight: 600; /* 表头字体加粗 */
  color: #303133; /* 表头字体颜色 */
  text-align: center; /* 表头居中 */
}

.table td {
  width: 10%;
}

.table-td {
  display: flex;
  justify-content: center;
}


::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
  flex-direction: row-reverse;
}

::v-deep .el-select__wrapper {
  background-color: transparent;
  box-shadow: none;
}

::v-deep .el-input-group__append {
  background-color: transparent;
  box-shadow: none;
}
</style>
